package com.lib.dao;

import com.lib.dao.ex.DaoException;
import com.lib.dao.ex.UpdateDaoException;
import com.lib.entity.Admin;
import com.lib.util.DBUtil;
import com.lib.util.ResultSetUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AdminDao {
    //以用户名查找管理员
    public Admin selectAdminByName(String name) throws DaoException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        conn = DBUtil.getConnection();
        Admin admin = null;
        try {
            ps = conn.prepareStatement("select * from user where name = ?");
            ps.setString(1,name);
            rs = ps.executeQuery();
            admin = ResultSetUtil.toBean(rs,Admin.class);
        } catch (Exception e) {
            throw new DaoException("数据库异常"+e.getMessage(),e);
        }finally {
            DBUtil.close(conn,ps,rs);
        }
        return admin;
    }
    //更新管理员密码
    public void updatePwd(String name,String opwd) throws UpdateDaoException, DaoException {
        Connection conn = null;
        PreparedStatement ps = null;
        conn = DBUtil.getConnection();
        int count = 0;
        try {
            ps = conn.prepareStatement("update user set pwd=? where name=?");
            ps.setString(1,opwd);
            ps.setString(2,name);
            count = ps.executeUpdate();
        }catch (Exception e){
            throw new DaoException("数据库错误"+e.getMessage(),e);
        }finally {
            DBUtil.close(conn,ps,null);
        }
        if(count != 1){
            throw new UpdateDaoException("更新密码失败");
        }
    }
}
